<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" @submit.prevent>
            <el-form-item label="区域名称" prop="name">
                <el-input
                v-model="queryParams.name"
                placeholder="请输入区域名称"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery()"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery()">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                <el-button type="primary" icon="DArrowLeft" @click="handlePreQuery" v-if="searchList.length > 1">上一级区域</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button
               type="primary"
               plain
               icon="Plus"
               @click="handleAdd()"
               v-hasPermi="['system:location:add']"
            >新增</el-button>
         </el-col>
        </el-row>
        <el-table
            height="500"
            v-loading="loading"
            :data="dataList"
            style="width: 1000px;">
            <el-table-column prop="name" label="区域名称" width="200" :show-overflow-tooltip="true">
              <template #default="scope">
                <el-button type="primary" link @click="handleQuery(scope.row.id, scope.row.name)">{{scope.row.name}}</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="districts" label="方位" width="150" :show-overflow-tooltip="true">
              <template #default="scope">
                <div v-for="(item, index) in system_location_districts" :key="index" v-show="item.value == scope.row.districts">
                  <div>{{ item.label }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="isEnable" label="状态" width="150">
              <template #default="scope">
                <div v-for="(item, index) in system_open_status" :key="index" v-show="item.value == scope.row.isEnable">
                  <el-tag :type="item.elTagType" v-if="item.elTagType">{{ item.label }}</el-tag>
                  <div v-else>{{ item.label }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="150" :show-overflow-tooltip="true" />
            <el-table-column label="操作" align="center" width="340" class-name="small-padding fixed-width" fixed="right"
              v-if="checkPermi(['system:location:add', 'system:location:edit', 'system:location:delete'])">
                <template #default="scope">
                    <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row.id, scope.row.name)" v-hasPermi="['system:location:add']">新增</el-button>
                    <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row.id)" v-hasPermi="['system:location:edit']">修改</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:location:delete']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog
            v-model="dialogData.show"
            :title="dialogData.title"
            width="600"
            :before-close="handleClose"
        >
            <el-form ref="dialogRef" label-width="80" :model="form" :rules="dialogData.rules">
                <el-row class="formBox">
                    <el-col :span="24">
                      <el-form-item label="所属区域" prop="parentId">
                        <SelectOption class="selectOptionBox" ref="parentIdSelectOption" placeHolder="请选择所属区域" title="区域选择"
                            v-model="form.parentId" :defaultFormValue="parentIdDefault" @loadOptions="parentIdDataLoad" v-if="dialogData.show && !formLoading"/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="区域名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入区域名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="方位" prop="districts">
                            <el-select v-model="form.districts" placeholder="请选择方位" clearable>
                                <el-option
                                    v-for="item in system_location_districts"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="排序" prop="sort">
                            <el-input v-model="form.sort" placeholder="请输入排序" type="number" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="状态" prop="isEnable">
                        <el-radio-group v-model="form.isEnable">
                          <el-radio
                              v-for="dict in system_open_status"
                              :key="dict.value"
                              :value="dict.value"
                          >{{ dict.label }}</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-button type="primary" :loading="formLoading" class="modalLoadingBox" v-if="formLoading">加载数据中</el-button>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="confirmForm">确 定</el-button>
                    <el-button @click="handleClose">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { areasList, addAreas, editAreas, deleteAreas, searchAreaById } from '@/api/system/location';
import SelectOption from '@/views/gasManage/components/SelectOption';
import { onMounted } from "vue";
import { ElLoading } from "element-plus";
import { checkPermi } from "@/utils/permission";
const { proxy } = getCurrentInstance();
const { system_open_status, system_location_districts } = proxy.useDict("system_open_status", "system_location_districts");
const searchList = ref([{
  id: '0',
  name: '主区域'
}]);
const queryParams = ref({});
const loading = ref(false);
const dataList = ref([]);
const dialogData = ref({
  show: false,
  title: '',
  rules: {
    parentId:  [{ required: true, message: "请选择所属区域", trigger: "blur" }],
    name: [{ required: true, message: "区域名称不能为空", trigger: "blur" }],
    districts: [{ required: true, message: "所属方位不能为空", trigger: "blur" }],
    sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
    code: [{ required: true, message: "邮政编码不能为空", trigger: "blur" }],
  }
})
const form = ref({
  parentId: '',
  name: '',
  districts: '',
  sort: '',
  isEnable: '1'
})
const formLoading = ref(false);
const parentIdDefault = ref('');
async function parentIdDataLoad(e){
  const { node, resolve } = e;
  let data = [];
  if(node.level === 0){
    data = [{
      id: String(0),
      name: '主分类'
    }]
  }else{
    data = await areasListApi({parentId: node.data.id});
  }
  proxy.$refs.parentIdSelectOption.handleLoadApi(data, node, resolve);
}
/** 搜索按钮操作 */
function handleQuery(id, name) {
  if(id){
    searchList.value.push({id: Number(id), name});
  }
  getList();
}
function handlePreQuery(){
  searchList.value.splice(searchList.value.length - 1, 1);
  handleQuery();
}
async function getList(){
  loading.value = true;
  queryParams.value.parentId = searchList.value[searchList.value.length - 1].id;
  let data = await areasListApi(queryParams.value);
  if(data && Array.isArray(data)) {
    dataList.value = data;
  }else{
    console.log(1)
  }
  loading.value = false;
}
function areasListApi(params){
  return new Promise(resolve => {
    areasList(params).then(res => {
      resolve(res.data);
    }).catch(() => {resolve(false)})
  })
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 新增按钮操作 */
async function handleAdd(id, name) {
  proxy.resetForm("dialogRef");
  parentIdDefault.value = '';
  handleModalShow('新增区域');
  if(id){
    parentIdDefault.value = name;
    form.value.parentId = id;
  }
}
function handleModalShow(name){
  dialogData.value.show = true;
  dialogData.value.title = name;
  form.value = {
    parentId: '',
    name: '',
    districts: '',
    sort: '',
    isEnable: '1',
  }
}
/** 修改按钮操作 */
async function handleEdit(id){
  proxy.resetForm("dialogRef");
  parentIdDefault.value = '';
  handleModalShow('修改区域');
  formLoading.value = true;
  let data = await getAreaByIdApi(id);
  form.value.id = data.id;
  form.value.parentId = data.parentId;
  form.value.name = data.name;
  form.value.districts = String(data.districts);
  form.value.sort = data.sort;
  form.value.isEnable = String(data.isEnable);
  if(data.parentId === '0'){
    parentIdDefault.value = '主分类';
  }else{
    let res = await getAreaByIdApi(data.parentId);
    parentIdDefault.value = res.name;
  }
  formLoading.value = false;
}
function getAreaByIdApi(id){
  return new Promise(resolve => {
    searchAreaById(id).then(res => {
      resolve(res.data);
    }).catch(() => {resolve(false)})
  })
}
/** 删除按钮操作 */
function handleDelete(row){
  proxy.$modal.confirm('是否确认删除区域名称为"' + row.name + '"的数据项?').then(()=>{
    deleteNow(row)
  }).catch(()=>{})
}
async function deleteNow(row){
  const loading = ElLoading.service({
    lock: true,
    text: '删除中~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  let data = await areasListApi({parentId: row.id});
  if(data && data.length){
    proxy.$modal.msgError(row.name+'存在下级区域，因此不可删除！');
  }else{
    deleteAreas(row.id).then(()=>{
      proxy.$modal.msgSuccess(row.name+'区域删除成功');
      handleQuery();
    })
  }
  loading.close();
}
function handleClose(){
  dialogData.value.show = false;
  dialogData.value.title = '';
}
function confirmForm(){
  console.log(form.value)
  proxy.$refs["dialogRef"].validate(valid=>{
      if(valid){
          if(dialogData.value.title === '新增区域'){
              addAreas(form.value).then(()=>{
                handleClose();
                proxy.$modal.msgSuccess('新增区域成功');
                handleQuery();
              })
          }else{
              editAreas(form.value).then(res=>{
                handleClose();
                proxy.$modal.msgSuccess('修改区域信息成功');
                handleQuery();
              })
          }
      }
  })
}
onMounted(()=>{
  getList();
})
</script>
<style lang="scss" scoped>
@import "@/assets/styles/public.scss";
.formBox{
  border-top: 1px solid $borderColor;
  padding-top: 30px;
  position: relative;
  .modalLoadingBox{
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, .7);
    border: 1px solid transparent;
    box-shadow: none;
    border-radius: 0px;
    position: absolute;
    top: 0;
    left: 0;
  }
}
.selectOptionBox{
  &:deep(.valueBox){
    background-color: white;
    border-radius: var(--el-border-radius-base);
    box-shadow: 0 0 0 1px var(--el-border-color) inset;
  }
}
</style>